/**
 * 费用申请模块业务入口
 */
import './presetVar'
import React, {Component} from 'react';
import {createPage, base, high, pageTo,promptBox} from 'nc-lightapp-front';
import {tableButtonClick,pageButtonClick, afterEvent,beforeEvent,onRowDoubleClick,refreshButtonClick} from './events';
import initTemplate,{routeChange} from './initTemplate';
import {getAfterEventParams} from 'src/erm/sscrppublic/common/utils/formulaUtils'
import {EditTable} from 'src/erm/sscrppublic/common/components/table';
import pubMessage from 'src/erm/sscrppublic/common/utils/pubMessage';
import getPageData from 'src/erm/sscrppublic/common/utils/getPageData';
import LinkQueryJkbxModel from 'src/erm/sscrppublic/common/linkquery/LinkQueryJkbxModel';
import Inspection from 'epmp/exports/components/Inspection';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';
import attachments from 'uap/common/components/getAttachmentInfo';
import ApprovalTrans from 'uap/common/components/approvalTrans';
import LinkChangeHistoryModel from '../link-change/LinkChange';
//引入侧边栏
import AuditSidebar from 'sscia/auditSidebar/components/auditSidebar'
const { getAttachments, getAttachmentsInfo } = attachments;
const { NCModal } = base;
import {
    BillStyle,
    BillHead,
    BillBody,
    Form,
    CardTableGroup,
    ButtonGroup,
    MultiButtonGroup
} from 'src/erm/sscrppublic/common/components/bill';

import {
    ProfileStyle,
    ProfileBody
} from 'src/erm/sscrppublic/common/components/profile';

import './index.less';

const pageButton = window.presetVar.pageButton;
window.assingUsers=[];
window.sureAssign = false;//确定指派
window.assignBillId = '';//有指派的情况下，第一次点保存提交实际保存成功的单据pk

class FYSQBill extends Component {

    constructor(props) {
        if (NODE_ENV == 'development') {
            window.NODE_ENV = 'development';
        }
        super();
            //初始化侧边栏
            this.auditSidebar = new AuditSidebar();
        this.state = {
            btn: [presetVar.body.body1 + presetVar.areaBtnAction.del, presetVar.body.body1 + presetVar.areaBtnAction.edit],
            showModal: false,
            showUploader: false,
            target: null,
            billId : '',
            sourceData: null,
            showLinkBudget: false,
            ShowApproveDetail: false,
            billtype: '',
            compositedata : '',
            compositedisplay : '',
            Title : '',
            linkData:'',
            uploaderBtnDisable: false, //附件上传按钮可用状态
            showLinkQueryChangeHistory: false,
            linkChangeHisData: '',
            djzt:'0',
            showAuditSidebar:false
        }
        this.close = this.close.bind(this);
        this.pubMessage = new pubMessage(props);
        this.getPageData = new getPageData(props);
        props.custom_this = this;
        
        initTemplate.call(this, props);

        // TOP NCCLOUD-61317 增加公式编辑后联动 chengwebc ADD
        props.setRelationAfterEventCallBack && props.setRelationAfterEventCallBack((props, changedField, changedArea, oldCard, newCard, index, rowId)=>{
            let params = getAfterEventParams(props, changedField, changedArea, oldCard, newCard, index, rowId);
            params.map((one)=>{
                afterEvent.call(this, props, one.moduleId, one.key, one.value, one.changedrows, one.index)
            })
        });

        props.use.form('head');
    }


    componentWillMount() {
           window.onbeforeunload = () => {
                let status = this.props.getUrlParam("status");
                if (status == 'edit'||status == 'add') return
           }
    }

    componentDidMount() {
      this.props.setHashChangeCallback(() => {
            routeChange.call(this, this.props);
      })
    }

    close() {
        this.setState({ showModal: false });
    }
    cancel(){
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info){
        this.setState({
            showLinkBudget: false
        })
    }
    openApprove = () => {
        this.setState({
            ShowApproveDetail: true
        })
    }

    closeApprove = () => {
        this.setState({
            ShowApproveDetail: false
        })
    }

    getAssginUser = (value) => {
        window.assingUsers = value;
        window.sureAssign = true;
        let props = this.props;
        if(props.getUrlParam('status') === 'browse'){
            pageButtonClick.call(this)[pageButton.billSubmit]();
        }else{
            pageButtonClick.call(this)[pageButton.billSaveSubmit]();
        }
        window.assignBillId = '';
    }

    turnOff(){
        window.presetVar.fromBtn = 'turnOff'
        this.setState({
            compositedisplay:false
        }) ;
        window.sureAssign = false;
        window.assingUsers = [];
        let id = this.props.getUrlParam('id') ? this.props.getUrlParam('id') : this.state.billId;
        if(id!=null && id.length>0){
     
        }
        let props = this.props;
        let billid = window.assignBillId;
        if(!billid){
            billid = props.form.getFormItemsValue('head', 'pk_mtapp_bill').value;
        }
        pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:'browse',id:billid,ts:new Date().getTime()});
        routeChange.call(this, this.props)
    }

    onBeforeEvent(props, moduleId, key, value,  index, record,status){
        window.presetVar.bodyChangeValuesAll = record;
        return true;
    }

    onHideUploader = () => {
        this.setState({
            showUploader: false,
        });
        let id = this.props.getUrlParam('id') ? this.props.getUrlParam('id') : this.state.billId;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId        
        getAttachments(id).then(lists => {
            this.props.button.setButtonTitle('fileManager', multiLang&&multiLang.get('201102SQFY-0031')/**'附件'**/ + ' ' + lists + ' ');
        })
    }

    renderErrorCenterState () {
        const { props } = this
        const { socket } = props;
        const status = props.form.getFormItemsValue('head', 'saga_status')
        if (!status || status.value !== '1') return null;
        
        this.props.button.toggleErrorStatus('head',{
            isError: true
        })

        const param = {
            headBtnAreaCode: 'head',
            formAreaCode: 'head',
            billtype: props.form.getFormItemsValue('head', 'saga_status').value,
            billpkname: 'pk_mtapp_bill',
            dataSource: 'erm.erbudgetmg.erbudetmg.card'
        }
        return props.socket.connectMesg(param)
    }
    toggleAuditSideBar(fromBtn) {
        //判断是否是提交 按钮或者保存提交按钮
        fromBtn = fromBtn||window.presetVar.fromBtn
       
        let props = this.props;
        let status = props.getUrlParam("status"); // 获取当前组件状态
        let billId = props.getUrlParam('billid') || props.getUrlParam('id') || this.state.billId || window.change_accessorybillid ||"";
            let billtype = window.presetVar.billtype
            if(billId==null || billId==""){
                
                let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", window.presetVar.bodys);
                if (billdata && billdata.head && billdata.head.head && billdata.head.head.rows[0]) {
                    billId = billdata.head.head.rows[0].values.pk_mtapp_bill.value;
                }
            }
            
            
        let param = {};

        param.pk_group = this.getFormHeadValueByKey('pk_group'); // "集团pk"
        param.billtypecode = this.getFormHeadValueByKey('pk_billtype'); // "单据类型code" 
        param.tradetypecode =  this.getFormHeadValueByKey('pk_tradetype'); // " 交易类型code"
        param.billid =  billId; // "单据主键pk"
        param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        param.iscreate = "Y"   // 注意应该是制单首次保存传Y,浏览态去掉这个参数！！！是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入 做初始化 智能审批
        param.isEdit = true;

        // param.pk_group = "0001A510000000000NKA"; // "集团pk"
        // param.billtypecode = "267X"; // "单据类型code" 
        // param.tradetypecode = "267X"; // " 交易类型code"
        // param.billid = "1001A510000000003V27"; // "单据主键pk"
        // param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        // param.iscreate =  "Y"  // 是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入
        // param.isEdit = true; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        console.log('param111111111111111111111',status,param)

        
        if(!param.billid){
            return
        }
        if(status==='add'){
            return
        }
         //展示后的回调
         this.auditSidebar.showSidebar(param,null,()=>{
        
            setTimeout(()=>{
                const auditSidebarObj = this.auditSidebar.getSidebarStatistical()
                console.log('1111111',auditSidebarObj)
                const {pointTree} = auditSidebarObj
                if(!pointTree.length){
                    this.setState({
                        showAuditSidebar:false
                    })
                    window.presetVar.auditCanSave = 0
                    return
                }
                this.setState({
                    showAuditSidebar:true
                })

                for(let i=0;i<pointTree.length;i++){
                    const leaf = pointTree[i]
                    if(leaf.children&&leaf.children.length){
                        if(leaf.children.some(item=>item.ispass==='N')){
                            window.presetVar.auditCanSave = 3 //目前需求只要有不通过的就提示风险
                            //1 严格控制 2风险提示
                            // if(leaf.children.some(item=>item.values.controltype=='1')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 1
                            //     break
                            // }else if(leaf.children.some(item=>item.values.controltype=='2')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 2
                            //     break
                            // }
                        }else{
                            window.presetVar.auditCanSave = 0
                        }
                    }
                }
                
                //展示风险弹窗
                if(fromBtn==='saveSubmit'&&this.props.getUrlParam("status")==='browse'&&window.presetVar.auditCanSave>0){
                    let multiLang = this.props.MutiInit.getIntl(2011);
                    promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: multiLang && multiLang.get('201102BCLF-0016'),
                        content: multiLang && multiLang.get('201102BCLF-0062'),
                        cancelBtnName:'收回',
                        beSureBtnClick: ()=>{
                            window.presetVar.auditCanSave = 0
                            
                        },
                        cancelBtnClick: () => {
                            pageButtonClick.call(this)[pageButton.billRecall]();
                            
                        }
                    })   
                }
            })
            
        })
    }

    getFormHeadValueByKey(key) { // 根据 form 获取 head 中的值
        return this.props.form.getFormItemsValue("head", key).value || '';
    }
    render() {
        const {djzt,showAuditSidebar} = this.state
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let btnModalConfig = {
            [pageButton.pageDel] : {
                // "2011-0004": "删除",
                // "2011-0005": "确认删除该单据吗？"
                title: multiLang && multiLang.get('2011-0004'),
                content: multiLang && multiLang.get('2011-0005'),
            },
            [pageButton.billInvalid]: {
                // "2011-0009": "作废",
                // "2011-0010": "确认作废该单据吗？"
                title: multiLang && multiLang.get('2011-0009'),
                content: multiLang && multiLang.get('2011-0010')
            },
            [pageButton.billEnable] : {
                // "2011-0011": "重启",
                // "2011-0012": "确认重启该单据吗？"
                title: multiLang && multiLang.get('2011-0011'),
                content: multiLang && multiLang.get('2011-0012')
            },
            [pageButton.billClose] : {
                // "2011-0007": "关闭"
                // "2011-0013": "确认关闭该单据吗？",
                title: multiLang && multiLang.get('2011-0007'),
                content: multiLang && multiLang.get('2011-0013')
            }
        }
          //侧拉抽屉
        const {table,DragWidthCom} = this.props;
        let { createSimpleTable} = table;
        let { showUploader,target } = this.state;
        const status = this.props.getUrlParam("status");
        let scene = this.props.getUrlParam("scene");
        console.log('单据场景==',scene)
        return (
            <div className='billWrapper'>
                {this.renderErrorCenterState()}
                <DragWidthCom
                    leftDom={
                        <BillStyle
                            {...this.props}
                        >
                            <BillHead
                                // "201102SQFY-0001": "费用申请单"
                                title={this.state.Title}
                                refreshButtonEvent={refreshButtonClick.bind(this)}
                            >
                                <ButtonGroup
                                    areaId="head"
                                    buttonEvent={pageButtonClick.bind(this)}
                                    modalConfig={btnModalConfig}
                                    sagasButtonVisible={true}
                                />

                                <Form
                                    areaId="head"
                                    onAfterEvent={afterEvent.bind(this)}
                                />
                            </BillHead>

                            <BillBody>
                                <CardTableGroup
                                    excludeTableAreaId={null}
                                    totalItemCode="orig_amount"
                                    modelSave={pageButtonClick.call(this)['pageSave']}
                                    modelDelRowBefore={(scope, moduleId, index) => {
                                        this.props.cardTable.delRowsByIndex(moduleId, index)
                                    }}
                                    onBeforeEvent={beforeEvent.bind(this)}
                                    onAfterEvent={afterEvent.bind(this)}
                                >
                                    <MultiButtonGroup buttonEvent={tableButtonClick.bind(this)} />
                                </CardTableGroup>

                                <div>
                                    {showUploader && < NCUploader
                                        disableButton={this.state.uploaderBtnDisable}
                                        billId={this.state.billId}
                                        targrt={target}
                                        onHide={this.onHideUploader}
                                        customize={{ 'pk_billtypecode': this.props.getUrlParam('tradetype'), "djdl": "ma" }}
                                        customInterface={
                                            {
                                                queryLeftTree: "/nccloud/erm/pub/ErmAttachmentTreeNodeQueryAction.do",
                                                queryAttachments: "/nccloud/erm/pub/ErmAttachmentQueryAction.do"
                                            }
                                        }
                                        placement={'bottom'} />
                                    }
                                </div>

                                <div>
                                    <ApproveDetail
                                        show={this.state.ShowApproveDetail}
                                        close={this.closeApprove}
                                        billtype={this.state.billtype}
                                        billid={this.state.billId}
                                    />
                                </div>
                                <LinkQueryJkbxModel
                                    show={this.state.showModal}
                                    linkData={this.state.linkData}
                                    close={() => this.setState({ showModal: false })}
                                    tradetype={window.presetVar.billtype}
                                    openBillId={this.state.billId}
                                    {...this.props} />

                            </BillBody>
                        </BillStyle>
                    }
                    rightDom={
                        this.auditSidebar.createComponent()
                    }
                    aside="right"
                    defLeftWid={showAuditSidebar && djzt !== '0' && status === 'browse' && (scene !== 'sscermlink' && scene !== "linksce" && scene !== "lc" && scene !== "approve" && scene !== "approvesce" && scene !== 'zycl')
                        ? "20%" : '0%'}
                ></DragWidthCom>
               
                <div>
                    <Inspection
                        show={ this.state.showLinkBudget }
                        sourceData = { this.state.sourceData }
                        cancel = { this.cancel.bind(this) }
                        affirm = { this.affirm.bind(this) }
                    />
                </div>
                <div>
                    {/*"201102FYYT-0003": "指派",*/}
                    {this.state.compositedisplay ? <ApprovalTrans
                        title={multiLang && multiLang.get('201102FYYT-0003')}
                        data={this.state.compositedata}
                        display={this.state.compositedisplay}
                        getResult={this.getAssginUser}
                        cancel={this.turnOff.bind(this)}
                     /> : ""}

                </div>

                {/* 联查变更历史 */}
                <LinkChangeHistoryModel
                    show={this.state.showLinkQueryChangeHistory}
                    linkData={this.state.linkChangeHisData}
                    close={() => this.setState({showLinkQueryChangeHistory: false})}
                    tradetype={window.presetVar.tradetype}
                    openBillId={this.state.billId}
                    {...this.props} />
            </div>
        );

    }
}

FYSQBill = createPage({
    mutiLangCode: '2011',
    billinfo:{
        billtype: 'extcard',  //虽然后台是一主多子数据结构，但是配置成extCard，编辑后请求公式验证会报错。因为会根据实际展现的表体数量来判断是一主多子还是一主一子。
        pagecode: presetVar.pageCode, 
        headcode: presetVar.head.head1,
        bodycode: presetVar.body.body1
    },
    orderOfHotKey: [presetVar.body.body1]
})(FYSQBill);

export default FYSQBill;
